//
//  ZZHomeWebViewController.m
//  WKWebView 与 JS
//
//  Created by 凉凉 on 2017/5/31.
//  Copyright © 2017年 凉凉. All rights reserved.
//

#import "ZZHomeWebViewController.h"
#import <WebKit/WebKit.h>
//#import "BHTestViewController.h"
//#import "LCLoginViewController.h"
//static const NSString *CompanyFirstDomainByWeChatRegister = @"lib.yewyw.com";
static const NSString *CompanyFirstDomainByWeChatRegister = @"h5.yewyw.com";
@interface ZZHomeWebViewController () <WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic,strong) UIProgressView *progressView;
//返回按钮
@property (nonatomic)UIBarButtonItem *backBtnItem;
//关闭按钮
@property (nonatomic)UIBarButtonItem *closeButtonItem;

//返回按钮
@property (nonatomic)UIBarButtonItem *clearBtnItem;

//分享按钮
@property (nonatomic)UIBarButtonItem *shareBtnItem;

@property (nonatomic,strong) NSString *cover;

@property (nonatomic,strong) NSString *title;

@property (nonatomic,assign) Boolean gotoIndex;


@end

@implementation ZZHomeWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{
                                                                      NSForegroundColorAttributeName: [UIColor blackColor],
                                                                      NSFontAttributeName: [UIFont systemFontOfSize:16]
                                                                      }];
    
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    // 请求网页数据
    [self loadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNotification) name:@"RELOADWBE" object:nil];
}


- (void)addNotification {
    [self.webView reload];
    NSLog(@"接受通知");
}


-(void)setupNav
{
    if([self.addressUrl containsString:@"main_page.html"]){
        self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo"]];
    }else{
        self.navigationItem.titleView = [[UIImageView alloc] init];
    }
    
    if([self.addressUrl containsString:@"will_publish.html"]){
        self.navigationController.navigationBar.hidden = YES;
    }else{
        self.navigationController.navigationBar.hidden = NO;
    }

    
}

- (void)viewWillAppear:(BOOL)animated{
    [self updateNavigationItems];
    [super viewWillAppear:animated];
}

-(void)loadData {
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.addressUrl]];
    [self.webView loadRequest:req];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
        self.progressView.hidden = NO;
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if(self.webView.estimatedProgress >=1.0f) {
            [self.progressView setProgress:1.0f animated:NO];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.progressView setProgress:0.0f animated:NO];
                self.progressView.hidden = YES;
            });
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
#pragma mark - WKNavigationDelegate
// 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"页面开始加载");
    [self setupNav];
}
// 加载完成
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
//    [self logoutWebView];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"当内容开始返回时调用");
}
// 内容加载失败时候调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"页面加载超时");
}
//跳转失败的时候调用
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"跳转失败");
}
//服务器开始请求的时候调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    
    NSURLRequest *request        = navigationAction.request;
    NSString     *scheme         = [request.URL scheme];
    NSString     *absoluteString = navigationAction.request.URL.absoluteString;
    NSLog(@"Current URL is %@",absoluteString);
    
    static NSString *endPayRedirectURL = nil;

    
    if([absoluteString containsString:@"data:image"]||[absoluteString containsString:@"favicon.ico"]){
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    if([absoluteString containsString:@"backurl=index"]){
        self.gotoIndex = true;
    }else{
        self.gotoIndex = false;
    }
    
  
    
    if ([absoluteString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![absoluteString containsString:[NSString stringWithFormat:@"redirect_url=xdx.%@://",CompanyFirstDomainByWeChatRegister]]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        
#warning Note : The string "xiaodongxie.cn://" must be configured by wechat background. It must be your company first domin. You also should configure "URL types" in the Info.plist file.
        
        // 1. If the url contain "redirect_url" : We need to remember it to use our scheme replace it.
        // 2. If the url not contain "redirect_url" , We should add it so that we will could jump to our app.
        NSString *redirectUrl = nil;
        if ([absoluteString containsString:@"redirect_url="]) {
            endPayRedirectURL = [self getParamValueByName:@"redirect_url" URLString:absoluteString];
            redirectUrl = [self modityParamValueByName:@"redirect_url" newValue:[NSString stringWithFormat:@"xdx.%@://?mt=8",CompanyFirstDomainByWeChatRegister] URLString:absoluteString];
//            self.addressUrl = absoluteString;
//            redirectUrl = [absoluteString stringByReplacingOccurrencesOfString:@"redirect_url=" withString:@"redirect_url=xdx.%@://?mt="];

        }else {
            redirectUrl = [absoluteString stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=xdx.%@://?mt=8",CompanyFirstDomainByWeChatRegister]];
        }
        
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        newRequest.URL = [NSURL URLWithString:redirectUrl];
        [webView loadRequest:newRequest];
        return;
    }
    
    if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
            decisionHandler(WKNavigationActionPolicyCancel);
            if ([scheme isEqualToString:[NSString stringWithFormat:@"xdx.%@",CompanyFirstDomainByWeChatRegister]]) {
    
            }
    
            // The var endPayRedirectURL was our saved origin url's redirect address. We need to load it when we return from wechat client.
            if (endPayRedirectURL) {
                NSString *decodeURL = [endPayRedirectURL stringByRemovingPercentEncoding];
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:decodeURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]];
            }

            [[UIApplication sharedApplication] openURL:request.URL options:@{} completionHandler:nil];
            return;
        }
    
       decisionHandler(WKNavigationActionPolicyAllow);
}





#pragma mark - WKScriptMessageHandler
// 从web界面中接收到一个脚本时调用
//window.webkit.messageHandlers.show.postMessage("我是js传递过来的数据");
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"****%@",message.name);
    
    
    if ([message.name isEqualToString:@"closePage"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    if ([message.name isEqualToString:@"AppModel"]) {
        NSLog(@"%@",message.body);
        self.cover = [message.body objectForKey:@"id"];
        self.title = [message.body objectForKey:@"title"];
        
    }
    
    
    if ([message.name isEqualToString:@"toLogin"]) {
        NSLog(@"%@",message.body);
    }
    
    if ([message.name isEqualToString:@"getLoginInfo"]) {
        NSLog(@"%@",message.body);
    }
    
}
- (void)showMsg:(NSString *)msg {
    if ([msg isEqual:[NSNull null]]) {
        msg = @"test";
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"j调用oc" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:NULL];
}


- (void)navButtonAction{
    // iOS调用js里的navButtonAction方法并传入两个参数
    [self.webView evaluateJavaScript:@"navButtonAction('Jonas',25)" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@=====%@",response,error);
    }];
}


// alert
//此方法作为js的alert方法接口的实现，默认弹出窗口应该只有提示信息及一个确认按钮，当然可以添加更多按钮以及其他内容，但是并不会起到什么作用
//点击确认按钮的相应事件需要执行completionHandler，这样js才能继续执行
////参数 message为  js 方法 alert(<message>) 中的<message>
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

// confirm
//作为js中confirm接口的实现，需要有提示信息以及两个相应事件， 确认及取消，并且在completionHandler中回传相应结果，确认返回YES， 取消返回NO
//参数 message为  js 方法 confirm(<message>) 中的<message>
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

// prompt
//作为js中prompt接口的实现，默认需要有一个输入框一个按钮，点击确认按钮回传输入值
//当然可以添加多个按钮以及多个输入框，不过completionHandler只有一个参数，如果有多个输入框，需要将多个输入框中的值通过某种方式拼接成一个字符串回传，js接收到之后再做处理
//参数 prompt 为 prompt(<message>, <defaultValue>);中的<message>
//参数defaultText 为 prompt(<message>, <defaultValue>);中的 <defaultValue>
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert]; [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}



#pragma mark ================ 自定义返回/关闭按钮 ================

-(void)updateNavigationItems {
    
    
    // 点击调用js方法
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"分享 copy"] style:UIBarButtonItemStylePlain target:self action:@selector(clickNavRightBtn)];
    
    if([self.addressUrl containsString:@"main_page.html"]){
        [self.navigationItem setLeftBarButtonItems:@[self.clearBtnItem] animated:NO];
    }
    else if (self.webView.canGoBack) {
        if(self.closeBtnEnable==false){
            [self.navigationItem setLeftBarButtonItems:@[self.backBtnItem] animated:NO];
        }else{
            [self.navigationItem setLeftBarButtonItems:@[self.backBtnItem,self.closeButtonItem] animated:NO];
        }
    }else{
        
        if(self.closeBtnEnable==false){
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
            [self.navigationItem setLeftBarButtonItems:@[self.backBtnItem]];
        }else{
            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
            [self.navigationItem setLeftBarButtonItems:@[self.backBtnItem,self.closeButtonItem]];
            
        }
    }
    
    if([self.addressUrl containsString:@"article_detail.html"]){
        [self.navigationItem setRightBarButtonItems:@[self.shareBtnItem] animated:NO];
    }else {
        [self.navigationItem setRightBarButtonItems:@[self.clearBtnItem] animated:NO];
    }
    
    
}
// 返回
-(void)clickBackBtn {
    [self updateNavigationItems];
    if (self.webView.canGoBack) {
        if(self.gotoIndex){
            self.addressUrl  =self.gotoIndexUrl;
            [self loadData];
        }else{
            [self.webView goBack];
        }
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
// 关闭
-(void)clickCloseBtn {
    [self.navigationController popViewControllerAnimated:YES];
}

//// oc 调用js
//-(void)clickNavRightBtn {
////    BHTestViewController *test = [[BHTestViewController alloc] init];
////    [self.navigationController pushViewController:test animated:YES];
//}

// oc 调用js
-(void)clickNavRightBtn {
    [self.webView evaluateJavaScript:@"articleInfo()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@=====%@",response,error);
    }];
}




#pragma mark - lazy
-(WKWebView *)webView {
    if (!_webView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 设置偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 10;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        // web内容处理池
        config.processPool = [[WKProcessPool alloc] init];
        
        // 通过JS与webview内容交互
        config.userContentController = [[WKUserContentController alloc] init];
        // 注入JS对象名称AppModel，当JS通过AppModel来调用时，
        // 我们可以在WKScriptMessageHandler代理中接收到
        
        [config.userContentController addScriptMessageHandler:self name:@"closePage"];
        [config.userContentController addScriptMessageHandler:self name:@"AppModel"];
        [config.userContentController addScriptMessageHandler:self name:@"toLogin"];
        [config.userContentController addScriptMessageHandler:self name:@"getLoginInfo"];

        
        
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
        //kvo 添加进度监控
        [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:NULL];
        
//        self.webView.scrollView.delegate = nil;

        // 设置代理
        _webView.navigationDelegate = self;
    }
    return _webView;
}


-(UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        [_progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
        [_progressView setFrame:CGRectMake(0, 64, self.view.frame.size.width, 1)];
        
        //设置进度条颜色
        [_progressView setTintColor:[UIColor colorWithRed:0.400 green:0.863 blue:0.133 alpha:1.000]];
    }
    return _progressView;
}


-(UIBarButtonItem *)backBtnItem {
    if (!_backBtnItem) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [btn setTitle:@"        " forState:UIControlStateNormal];
        [btn setTitleColor:self.navigationController.navigationBar.tintColor forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"Sback"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clickBackBtn) forControlEvents:UIControlEventTouchUpInside];
        [btn sizeToFit];
        _backBtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _backBtnItem;
}



-(UIBarButtonItem *)closeButtonItem {
    if (!_closeButtonItem) {
//        _closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(clickCloseBtn)];
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [btn setTitle:@"     " forState:UIControlStateNormal];
        [btn setTitleColor:self.navigationController.navigationBar.tintColor forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clickCloseBtn) forControlEvents:UIControlEventTouchUpInside];
        [btn sizeToFit];
        _closeButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];

    }
    return _closeButtonItem;
}


-(UIBarButtonItem *)clearBtnItem {
    if (!_clearBtnItem) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [btn setTitle:@"     " forState:UIControlStateNormal];
        [btn setTitleColor:self.navigationController.navigationBar.tintColor forState:UIControlStateNormal];
//        [btn setImage:[UIImage imageNamed:@"Sback"] forState:UIControlStateNormal];
//        [btn addTarget:self action:@selector(clickBackBtn) forControlEvents:UIControlEventTouchUpInside];
        [btn sizeToFit];
        _clearBtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _clearBtnItem;
}


-(UIBarButtonItem *)shareBtnItem {
    if (!_shareBtnItem) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [btn setTitle:@"" forState:UIControlStateNormal];
        [btn setTitleColor:self.navigationController.navigationBar.tintColor forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"分享 copy"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clickNavRightBtn) forControlEvents:UIControlEventTouchUpInside];
        [btn sizeToFit];
        _shareBtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _shareBtnItem;
}

-(void)dealloc {
    NSString *sysVersion = [[UIDevice currentDevice] systemVersion];
    if([sysVersion integerValue]>=10){
        [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"closePage"];
        [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"AppModel"];
        [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"toLogin"];
        [[self.webView configuration].userContentController removeScriptMessageHandlerForName:@"getLoginInfo"];
        [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    }else if([sysVersion integerValue]==9){
//         self.webView.scrollView.delegate = nil;
    }else{
        
    }

}


- (NSString *)getParamValueByName:(NSString *)name URLString:(NSString *)url {
    if (url.length == 0 || name.length == 0) {
        return nil;
    }
    
    NSError *error;
    NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", name];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return nil;
}

- (NSString *)modityParamValueByName:(NSString *)name newValue:(NSString *)newValue URLString:(NSString *)url {
    if (url.length == 0 || name.length == 0) {
        return nil;
    }
    
    NSError *error;
    NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", name];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        NSString *newStr = [url stringByReplacingOccurrencesOfString:tagValue withString:newValue];
        return newStr;
    }
    
    return nil;
}


@end
